package com.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dto.AddressDto;
import com.po.Address;
import com.result.Result;
import com.service.AddressService;
import com.vo.AddressVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/address/")
public class AddressController {

    private final AddressService addressService;

    /**
     * 增加收货地址
     * @param addressDto
     * @return
     */
    @PostMapping("save")
    public Result save(@RequestBody AddressDto addressDto){
        log.info("新增地址：{}",addressDto);
        Address address = new Address();
        BeanUtil.copyProperties(addressDto,address);
        address.setUserId(StpUtil.getLoginIdAsLong());
        //判断是否为第一次添加地址，第一次添加地址必须设为默认地址
        int count = addressService.count();
        if (count == 0){
            address.setIsDefault(1);
            addressService.save(address);
            return Result.success();
        }
        //判断新增地址是否为默认地址
        if (address.getIsDefault() == 1){
            QueryWrapper<Address> wrapper = new QueryWrapper<Address>()
                    .in("is_default", 1);
            Address one = addressService.getOne(wrapper);
            //如果已有默认地址则需要修改
            if (ObjectUtil.isNotEmpty(one)) {
                UpdateWrapper<Address> updateWrapper = new UpdateWrapper<Address>()
                        .setSql("is_default = 0")
                        .in("id", one.getId());
                addressService.update(null,updateWrapper);
            }
        }
        addressService.save(address);
        return Result.success();
    }

    /**
     * 修改默认地址
     * @param id
     * @return
     */
    @PutMapping("update")
    public Result update(@RequestParam Long id){
        log.info("修改默认地址:{}",id);
        //查询出原本默认地址
        QueryWrapper<Address> wrapper = new QueryWrapper<Address>()
                .in("is_default", 1);
        Address one = addressService.getOne(wrapper);
        //已有默认地址则需要修改
        UpdateWrapper<Address> updateWrapper = new UpdateWrapper<Address>()
                .setSql("is_default = 0")
                .in("id", one.getId());
        addressService.update(null,updateWrapper);
        //修改默认地址
        UpdateWrapper<Address> updateWrapper1 = new UpdateWrapper<Address>()
                .setSql("is_default = 1")
                .in("id", id);
        addressService.update(null,updateWrapper1);
        return Result.success();
    }

    /**
     * 修改地址信息
     * @param addressDto
     * @return
     */
    @PutMapping("revise")
    public Result revise(@RequestBody AddressDto addressDto){
        log.info("修改地址信息：{}",addressDto);
        String city = addressDto.getCity();
        String contact = addressDto.getContact();
        String mobile = addressDto.getMobile();
        String province = addressDto.getProvince();
        String street = addressDto.getStreet();
        String town = addressDto.getTown();
        LambdaUpdateWrapper<Address> wrapper = new LambdaUpdateWrapper<Address>()
                .set(city != null && !city.equals(""), Address::getCity, city)
                .set(contact != null && !contact.equals(""), Address::getContact, contact)
                .set(mobile != null && !mobile.equals(""), Address::getMobile, mobile)
                .set(province != null && !province.equals(""), Address::getProvince, province)
                .set(street != null && !street.equals(""), Address::getStreet, street)
                .set(town != null && !town.equals(""), Address::getTown, town)
                .in(Address::getId, addressDto.getId());
        addressService.update(null,wrapper);
        return Result.success();
    }

    /**
     * 查询用户全部地址
     * @return
     */
    @GetMapping("list")
    public Result<List<AddressVo>> list(){
        log.info("查询用户全部地址：");
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, StpUtil.getLoginIdAsLong());
        List<Address> addressList = addressService.list(wrapper);
        List<AddressVo> addressVoList = new ArrayList<>();
        addressList.forEach(address -> {
            AddressVo addressVo = new AddressVo();
            BeanUtil.copyProperties(address,addressVo);
            addressVoList.add(addressVo);
        });
        return Result.success(addressVoList);
    }

    /**
     * 查询地址详细信息
     * @param id
     * @return
     */
    @GetMapping("get")
    public Result<AddressVo> get(@RequestParam Long id){
        log.info("查询地址详细信息：{}",id);
        Address address = addressService.getById(id);
        AddressVo addressVo = new AddressVo();
        BeanUtil.copyProperties(address,addressVo);
        return Result.success(addressVo);
    }

    /**
     * 删除地址信息
     * @param id
     * @return
     */
    @DeleteMapping("delete")
    public Result delete(@RequestParam Long id){
        log.info("删除地址信息：{}",id);
        addressService.removeById(id);
        return Result.success();
    }

    /**
     * 查询默认地址
     * @return
     */
    @GetMapping("iget")
    public Result<AddressVo> iget() throws Exception {
        log.info("查询默认地址:");
        QueryWrapper<Address> wrapper = new QueryWrapper<Address>()
                .in("is_default", 1);
        Address address = addressService.getOne(wrapper);
        if (ObjectUtil.isEmpty(address)){
            throw new Exception("未查询到默认地址，请设置！");
        }
        AddressVo addressVo = new AddressVo();
        BeanUtil.copyProperties(address,addressVo);
        return Result.success(addressVo);
    }
}
